#include "RecentFiles.h"
#include "RecentFilesViewQMenu.h"


RecentFilesViewQMenu::RecentFilesViewQMenu(RecentFiles& model, QWidget *parent) :
        QMenu(parent), RecentFilesView(model)
{
    m_actionSignalMapper = new QSignalMapper(this);
    for (int i = 0; i < m_model.maxNumRecentFiles(); i++)
    {
        QAction *action = new QAction(0);
        connect(action, SIGNAL(triggered()), m_actionSignalMapper, SLOT(map()));
        m_actionSignalMapper->setMapping(action, i);
        m_actions.push_back(action);
        addAction(action);
    }

    connect(m_actionSignalMapper, SIGNAL(mapped(int)), this, SLOT(slotRecentFileActivated(int)));
}

void RecentFilesViewQMenu::slotRecentFileActivated(int index)
{
    QString name = m_model.filename(index);
    recentFileSelected(m_model.filename(index));
}

void RecentFilesViewQMenu::update()
{
    int numRecentFiles = m_model.count();

    // Set all actions to be hidden.
    foreach (QAction *action, m_actions)
        action->setVisible(false);

    // For each recent file, set the corresponding action to visible.
    for (int i = 0; i < numRecentFiles; i++)
    {
        QAction *action = m_actions.at(i);
        QString filename = m_model.filename(i);

        action->setText(filename);
        action->setStatusTip(QString("Open recent file: %1").arg(filename));
        action->setVisible(true);
    }
}
